package com.mgq.netty.chat.handler;

import com.mgq.netty.chat.message.ChatRequestMessage;
import com.mgq.netty.chat.message.ChatResponseMessage;
import com.mgq.netty.chat.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author MaGuangQi
 * @description
 * @date 2021-12-08 10:27
 **/
@ChannelHandler.Sharable
public class ChatRequestMessageHandler  extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        String to = msg.getTo();
        Channel channel = SessionFactory.getSession().getChannel(to);
        //在线
        if (channel != null) {
            //给发送消息
            ChatResponseMessage responseMessage = new ChatResponseMessage(msg.getTo(), msg.getContent());
            channel.writeAndFlush(responseMessage);
        } else {
            //不在线
            ChatResponseMessage responseMessage = new ChatResponseMessage(false, "用户不在线");
            ctx.writeAndFlush(responseMessage);
        }
    }
}
